/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package backupmonografia;

import java.io.File;
import java.security.Security;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SimpleMail {

    private String mailhost = "smtp.gmail.com";

    public synchronized void sendMail(String subject, String body, String sender,
            String recipients, String password, File arquivo) throws Exception {

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        Session session = Session.getDefaultInstance(props, new AutenticadorGmail(sender, password));

        session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        InternetAddress from = new InternetAddress(sender);
        message.setFrom(from);

        if (recipients.indexOf(',') > 0) {
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
        } else {
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
        }

        message.setSubject(subject);

        // cria a primeira parte da mensagem
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(body);

        // cria a segunda parte da mensagem
        MimeBodyPart mbp2 = new MimeBodyPart();

        // anexa o arquivo à mensagem
        FileDataSource fds = new FileDataSource(arquivo);
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());

        // Cria o Multipart a adiciona as duas partes a ele
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        message.setContent(mp);

        Transport.send(message);

    }
}
